package com.gw.redis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component
public class RedisHashUtil { //操作Redis的hash缓存
    @Autowired //自动注入RedisTemplate
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 写入缓存
     * @param key
     * @param field
     * @param value
     * @return
     */
    public boolean hmSet(final String key,String field,Object value ){
        boolean result=false;
        try {
            redisTemplate.opsForHash().put(key,field,value);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 读取缓存
     * @param key
     * @return
     */
    public Object hGet(final String key,String filed){
        return redisTemplate.opsForHash().get(key,filed);
    }
    public Map hGetAll(final String key){
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 更新缓存
     * @param key
     * @param failed
     * @param value
     */
    public void hGetAndSet(final String key,String failed,Object value){
        List<Object> list=redisTemplate.opsForHash().values(key);
        Iterator iterator =list.iterator();
        while(iterator.hasNext()){
            if (iterator.next().equals(failed)){
                redisTemplate.opsForHash().delete(key,failed);
                break;
            }
        }
        redisTemplate.opsForHash().put(key,failed,value);
    }

    /**
     * 删除缓存
     * @param key
     * @param failed
     * @return
     */
    public boolean hDelete(final String key,String failed){
        boolean result=false;
        try {
            redisTemplate.opsForHash().delete(key,failed);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
